'use strict';


let fs = require('fs');
let path = require('path');
let router = require('koa-router')();


 function searchAllControllerFiles(dir){

    let files = fs.readdirSync(dir);
    let controllers = files.filter((name)=>{

       return name.endsWith('.js') && name !=='index.js'

    })
    return controllers;
 }



 function registRoutes(files){

    files.forEach(element => {
        
        let tmpFiles =path.join(__dirname,element);
        let tmpRouters = require(tmpFiles);

        for(var x in tmpRouters){

            let type = tmpRouters[x][0];
            let fn = tmpRouters[x][1];

            if(type ==='get'){

                router.get(x,fn);

            }
            else if(type ==='put'){
                router.put(x,fn);
            }
            else if(type === 'post'){
                router.post(x,fn);
            }
            else if(type === 'delete'){
                router.delete(x,fn);
            }

        }

    });
 }


 module.exports = function(){

    let a = __dirname;
    let b = searchAllControllerFiles(a);

    registRoutes(b);

    return router.routes();
 }